import AntModal from '@/components/pt/dialog/AntModal'
import { getBizReceiveOrder, addBizReceiveOrder, updateBizReceiveOrder } from '@/api/biz/bizReceiveOrder'
import SelectUser from "@/components/pt/selectUser/SelectUser";
import SelectDept from "@/components/pt/selectDept/SelectDept";
import BizProduct from "@/views/biz/bizorder/modules/BizProduct";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import { listBizWarehouseSpaceByproductId } from "@/api/biz/bizWarehouseSpace";
import { listBizProductInventory } from "@/api/biz/bizProductInventory"
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import {randomUUID} from '@/utils/util';

export default {
  name: 'CreateForm',
  props: {
    statusOptions: {
      type: Array,
      required: true
    },
    warehouseIdOptions: {
      type: Array,
      required: false
    }
  },
  components: {
    AntModal,
    SelectUser,
    SelectDept,
    BizProduct,
    AdvanceTable

  },
  mixins: [tableDragResizeMixin],
  data() {
    return {
      showProductModal: false,
      multiple: false,
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      formTitle: '添加领用出库单',
      // 表单参数
      form: {},
      spaceList: [],
      // 选中的数据集合
      selectedRows: [],
      rules: {
        tenantId: [{ required: true, message: '租户id不能为空', trigger: 'blur' }],
        spaceId: [{ required: true, message: '仓位不能为空', trigger: 'blur' }],
      },
      columns: [
        {
          title: '存货编码',
          dataIndex: 'productCode',
          align: 'center',
          width: '15%'
        },
        {
          title: '仓位',
          dataIndex: 'spaceId',
          align: 'center',
          width: '5%',
          scopedSlots: {
            customRender: 'spaceIdSlot'
          },
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width: '5%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width: '10%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'center',
          width: '10%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width: '8%'
        },
        // {
        //   title: '库存',
        //   dataIndex: 'stock',
        //   align: 'center',
        //   width: '8%'
        // },
        {
          title: '数量',
          dataIndex: 'receiveNumber',//保存需要拷贝到number
          align: 'center',
          scopedSlots: {
            customRender: 'numberSlot'
          },
          width: '7%'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          scopedSlots: {
            customRender: 'unitSlot'
          },
          width: '7%'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remarkSlot'
          },
          width: '10%'
        }
      ],
      list: [],
      selectedRowKeys: [],
      ids: [],
    }
  },
  filters: {},
  created() {
    this.initColumnsSetting('initDetail')
  },
  computed: {},
  watch: {},
  mounted() { },
  methods: {
    onClose() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        receiveCode: undefined,

        receiveDate: undefined,

        receiveUserId: undefined,

        receiveUserName: undefined,

        tenantId: undefined,

        status: '0',

        detailList: [],

      }
    },
    /**
     * 
     * @param {string} value 
     * @param {obj} record 
     * @param {number} index 
     */
    changeSpace(value, record, index) {
      let params = {
        warehouseId: this.form.warehouseId,
        productId: record.id,
        spaceId: value
      }
      listBizProductInventory(params).then(res => {
        let data = res.data.list
        if (data.length === 0) {
          record.stock = 0
          record.assistNumberA = 0
          record.assistNumberB = 0
          this.form.detailList.splice(index, 1, record)
        } else if (data.length === 1) {
          //
          
          record.assistNumberA = data[0].assistNumberA
          record.assistNumberB = data[0].assistNumberA
          // 查找单位
          this.unitChange(record.unit,record,index)
        } else {
          console.log('库存异常 :>> ');
        }
        console.log(' this.form.detailList :>> ', this.form.detailList);
      })
    },
    /**
     * @单位change
     * @param {*} e 单位index
     * @param {*} record 
     * @param {*} index 
     */
    unitChange(e, record, index) {
      let item = this.form.detailList[index]
      console.log('item :>> ', item);
      switch (e) {
        case 1:
          item.stock = item.number
          break;
        case 2:
          item.stock = item.assistNumberA
          break;
        case 3:
          item.stock = item.assistNumberB
          break;
        default:
          break;
      }
      this.form.detailList.splice(index,1,item)
    },
    /**
     * @删除
     * @returns 
     */
    handleDeleteRows() {
      console.log('this.form.detailList :>> ', this.form.detailList);
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.form.detailList = this.form.detailList.filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.id) && !this.selectedRowKeys.includes(v.uuid))
          this.selectedRowKeys = []
          this.multiple = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.formTitle = '添加领用出库单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.spinning = !this.spinning
      const bizReceiveOrderId = row.id
      getBizReceiveOrder(bizReceiveOrderId).then(response => {
        this.form = response.data
        this.form.receiveUserId = { ids: this.form.receiveUserId, names: this.form.receiveUserName }
        this.form.detailList = this.form.detailList.map(v => {
          v.unit = +v.unit
          v.spaceList = [{ id: v.spaceId, postion: v.spaceName }]
          v.receiveNumber = v.number
          return v
        })
        console.log('this.form.detailList :>> ', this.form.detailList);
        this.formTitle = '修改领用出库单'
        this.spinning = !this.spinning
        this.selectWarehouse()
      })
    },
    validateStock(){
      for (var i = 0; i < this.form.detailList.length; i++) {
        let item = this.form.detailList[i]
        if (item.receiveNumber > item.stock) {
          this.$message.error(`第${i+ 1}行库存不足`)
          return false
        }
      }
      return true
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid && this.validateStock()) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          saveForm.detailList.forEach(val=>{
            val.number = val.receiveNumber
          })
          if (this.form.receiveUserId !== undefined) {
            saveForm.receiveUserId = this.form.receiveUserId.ids
            saveForm.receiveUserName = this.form.receiveUserId.names
          }
          if (this.form.id !== undefined) {
            updateBizReceiveOrder(saveForm).then(response => {
              this.$message.success('更新成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
            })
          } else {
            addBizReceiveOrder(saveForm).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
            })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back() {
      const index = '/biz/bizreceiveorder/index'
      this.$router.push(index)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      console.log('this.selectedRows :>> ', this.selectedRows);
      console.log('this.selectedRowKeys :>> ', this.selectedRowKeys);
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    handleSubUpdate() {

    },
    handleSubDelete(row) {
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          let selectedList = JSON.parse(JSON.stringify(that.list));
          selectedList.forEach((item, index) => {
            if (row.id) {
              that.list = that.list.filter(item => item.id != row.id)
              return;
            } else {
              that.selectedRows.forEach(item2 => {
                that.list = that.list.filter(item => item.id != item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel() { }
      })
    },
    handleAddProduct() {
      this.showProductModal = true
      this.$nextTick(() => {
        this.$refs.bizProduct.queryParam.inventoryFlag = 1
        this.$refs.bizProduct.queryParam.warehouseId = this.form.warehouseId
        this.$refs.bizProduct.handleAddProduct(this.list);
      })
    },
    spaceFocus(record, index) {
      listBizWarehouseSpaceByproductId(this.form.warehouseId, record.productId).then(res => {
        record.spaceList = res.data;
        this.form.detailList.splice(index, 1, record)
      });
    },
    selectWarehouse(bol = false) {
      if(!this.form.id) return
      listBizWarehouseSpaceByproductId(this.form.warehouseId, this.form.id).then(res => {
        this.spaceList = res.data;
        if (bol) {
            // 仓库变更需要清空已选择的仓位，和已计算的库存
          this.form.detailList.forEach(val=>{
            this.$set(val,'stock','')
            this.$set(val,'spaceId','')
            this.$set(val,'receiveNumber',0)
          })
        }
      });
    },
    selectProduct(selectedRows) {
      selectedRows.forEach(item => {
        item.unitList = [];
        item.unitList.push({
          key: 1,
          name: item.unit
        })
        item.unitList.push({
          key: 2,
          name: item.assistUnitA
        })
        item.unitList.push({
          key: 3,
          name: item.assistUnitB
        })
        item.receiveNumber = 0;
        item.tempSalePrice = item.salePrice;
        if (item.defaultWarehousingUnit == 2) {
          item.unit = 2
          item.unitPrice = item.salePriceA
        } else if (item.defaultWarehousingUnit == 3) {
          item.unit = 3
          item.unitPrice = item.salePriceB
        } else {
          item.unit = 1;
          item.unitPrice = item.salePrice;
        }
        item.totalAmount = 0.00;
        item.productId = item.id
        item.uuid = randomUUID()
        this.$forceUpdate();
      })

      this.form.detailList = [...this.form.detailList, ...selectedRows];
    },
    handleChange(info) {
      if (info.file.status == 'done') {
        this.fileList = info.fileList;
      }
    },
    handleRemove(info) {
      this.fileList = this.fileList.filter(function (item) {
        return item.uid != info.uid
      })
    },

    selectUnit(record) {
      if (record.unit == 1) {
        record.unitPrice = record.purchasesPrice;
      } else if (record.unit == 2) {
        record.unitPrice = record.purchasesPriceA;
      } else if (record.unit == 3) {
        record.unitPrice = record.purchasesPriceB;
      }
      record.totalAmount = record.unitPrice * record.number;
      this.$forceUpdate();
    },
    
    /**
     * 设置table的row的class
     * @param {obj} row 
     * @param {number} index 
     */
     getRowClassName(row,index){
      let arr = this.form.detailList.filter(v=>v.productCode === row.productCode)
      if (arr.length > 1) {
        return 'multiple_table_row'
      }
    },

  }
}
